package user

import (
	"encoding/json"
	"my-web-app/user/entity"
	"net/http"
	"strconv"
)

// 模拟的用户列表
var users = []entity.User{
	{ID: 1, Name: "Alice", Age: 30},
	{ID: 2, Name: "Bob", Age: 25},
}

// getUserList 处理获取用户列表的请求
func getUserList(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(users)
}

// getUserByID 处理根据ID获取单个用户的请求
func getUserByID(w http.ResponseWriter, r *http.Request) {
	idStr := r.URL.Query().Get("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		http.Error(w, "Invalid user ID", http.StatusBadRequest)
		return
	}

	for _, user := range users {
		if user.ID == id {
			w.Header().Set("Content-Type", "application/json")
			json.NewEncoder(w).Encode(user)
			return
		}
	}
	http.Error(w, "User not found", http.StatusNotFound)
}

// createUser 处理创建新用户的请求（这里为了简化，只是模拟）
func createUser(w http.ResponseWriter, r *http.Request) {
	// 假设这里从请求体中解析出用户数据...
	// 这里我们直接创建一个新用户作为示例
	newUser := entity.User{ID: len(users) + 1, Name: "NewUser", Age: 35}
	users = append(users, newUser)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(newUser)
}

func UserAPI() {
	// 注册路由
	http.HandleFunc("/users", getUserList)
	http.HandleFunc("/user", getUserByID) // 注意：这里为了简化没有使用/user/{id}，而是使用查询参数
	http.HandleFunc("/user/create", createUser)
}
